package com.yixun.qfbao.controller.agency.weapp;

import java.util.Map;

import javax.validation.Valid;

import com.yixun.qfbao.api.service.*;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.model.CustomerCount;
import com.yixun.qfbao.response.my.GetCustomerCountRes;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.yixun.qfbao.annotations.History;
import com.yixun.qfbao.apidto.base.CommonReqDTO;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.request.BaseRequest;
import com.yixun.qfbao.request.GenericContentRequest;
import com.yixun.qfbao.request.GenericIdRequest;
import com.yixun.qfbao.request.my.GetPersonalDeptQrCodeUrlReqDto;
import com.yixun.qfbao.request.my.UpdatePartnerInfoReqDto;
import com.yixun.qfbao.response.BaseResponse;
import com.yixun.qfbao.response.CommonResponse;
import com.yixun.qfbao.response.my.AgencyPartnerInfo;
import com.yixun.qfbao.response.my.Principal;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.QiNiuUtil;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.utils.LoginUtils;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author zilong.liu
 * @date 2020-8-3
 * @desc
 *
 */
@Api(tags = {"分销小程序-我的"})
@Controller
@ResponseBody
@RequestMapping("/agency/weapp/my")
public class MyController {
	
	@Autowired
	LoginUtils loginUtils;
	
	@Autowired
	PersonnelService personnelService;
	
	@Autowired
	DepartmentDao departmentDao;

	@Autowired
	ThirdPartyApiService thirdPartyApiService;
	
	@Autowired
	MyService myService;
	
	@Autowired
	PartnerInfoService partnerInfoService;
	
	@Autowired
	CompanyService companyService;
	@Autowired
	ChannelReportService channelReportService;

	@Autowired
	private PremisesApiService premisesService;
	
	/**
	 *	 退出登录
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="退出登录", response = CommonResponse.class)
	@PostMapping("/loginExit")
	public CommonResponse loginExit(@RequestBody @Valid CommonReqDTO commonReqDto) {
		String userId = commonReqDto.getUserId();
		PartnerInfo partnerInfo = loginUtils.getUser(Long.parseLong(userId));
		if (null != partnerInfo) {
			loginUtils.removeUser(userId);
			
			myService.loginExit(commonReqDto.getLoginType(), commonReqDto.getCompanyUuid(), userId);
		}
		CommonResponse res = new CommonResponse(ResultEnum.SUCCESS.getNo(), "退出成功");
		return res;
	}
	
	/**
	 * 修改密码，修改密码之后需要退出登录
	 * @param reqDto
	 * @return
	 */
	@ApiOperation(value="修改密码", response = CommonResponse.class)
	@PostMapping("/updatePwd")
	public CommonResponse updatePwd(@RequestBody @Valid BaseRequest<com.yixun.qfbao.request.my.UpdatePwdReqDto> reqDto) {
		String userId = reqDto.getUserId();
		UpdatePwdReqDto updatePwdReqDto = new UpdatePwdReqDto();
		updatePwdReqDto.setUserId(userId);
		updatePwdReqDto.setNewPassword(reqDto.getData().getNewPassword());
		updatePwdReqDto.setOldPassword(reqDto.getData().getOldPassword());
		updatePwdReqDto.setConfirmPassword(reqDto.getData().getConfirmPassword());
		
		CommonResponse res = new CommonResponse(ResultEnum.SUCCESS.getNo(), "密码修改成功");
		try {
			personnelService.updatePwd(updatePwdReqDto);
		} catch (TServerException e) {
			res.setCode(ResultEnum.FAIL.getNo());
			res.setMsg(e.getErrorMsg());
		}
		loginUtils.removeUser(userId);
		
		myService.loginExit(reqDto.getLoginType(), reqDto.getCompanyUuid(), userId);
		
		return res;
	}
	
	/**
	 * 获取渠道支持
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="获取渠道支持")
	@PostMapping("/getPrincipalByPartnerId")
	public BaseResponse<Principal> getPrincipalByPartnerId(@RequestBody @Valid CommonReqDTO reqDto) {
		String userId = reqDto.getUserId();
		Map<String, Object> principle = departmentDao.getPrincipalByPartnerId(Long.parseLong(userId));
		BaseResponse<Principal> res = new BaseResponse<>();
		res.setCode(ResultEnum.SUCCESS.getNo());
		if(principle == null) {
			return res;
		}
		Principal principal = new Principal();
		principal.setAccountName(String.valueOf(principle.get("principalName")));
		principal.setPhone(String.valueOf(principle.get("phone")));
		principal.setDepartmentName(String.valueOf(principle.get("companyName")));
		res.setData(principal);
		return res;
	}
	
	/**
	 * 生成二维码
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="生成二维码")
	@PostMapping("/getQrCode")
	public BaseResponse<String> getQrCode(@RequestBody @Valid BaseRequest<GenericContentRequest> reqDto) {
		CreateQRCodeReqDto createQRCodeReqDto = new CreateQRCodeReqDto();
		createQRCodeReqDto.setContent(reqDto.getData().getContent());
		
		// 从缓存获取上传到七牛的URL
		BaseResponse<String> res = new BaseResponse<>();
		
		//如果没有生成，则生成二维码，上传至七牛，并将生成的七牛的链接
		String qrCode = thirdPartyApiService.getQrCodeQiniuUrl(reqDto.getData().getContent());
		if(StringUtils.isNotBlank(qrCode)){
            qrCode =  qrCode.replaceAll("\n","");
            qrCode = qrCode.replaceAll("\r","");
        }
		res.setData(qrCode);
		return res;
	}
	
	
	/**
	 * 获取部门的注册二维码
	 * @param commonReqDto
	 * @return
	 */
	@History(sinceTime = "2021-02-07")
	@ApiOperation(value="获取当前部门的二维码.入参传递为最下级ID")
	@PostMapping("/getDepartmentQrCodeUrl")
	public BaseResponse<String> getDepartmentQrCodeUrl(@RequestBody @Valid BaseRequest<GenericIdRequest> reqDto) {
		
		String fileUrl = myService.getQrCodeUrl(reqDto.getUserId(), reqDto.getData().getId(), reqDto.getCompanyUuid(), "partnerDeptQrcodeService");
		// 从缓存获取上传到七牛的URL
		BaseResponse<String> res = new BaseResponse<>();

		if(fileUrl.indexOf("失败") > -1) {
			res.setMsg(fileUrl);
			res.setCode(ResultEnum.FAIL.getNo());
			return res;
		}
		
		res.setData(fileUrl);
		res.setCode(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	/**
	 *  获取部门的注册二维码，并且二维码上携带个人标识
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="获取部门的注册二维码，并且二维码上携带个人标识")
	@PostMapping("/getPersonalDeptQrCodeUrl")
	public BaseResponse<String> getPersonalDeptQrCodeUrl(@RequestBody @Valid BaseRequest<GetPersonalDeptQrCodeUrlReqDto> reqDto) {
		String userId = reqDto.getUserId();
		Long deptId = reqDto.getData().getDeptId();
		String fileUrl = myService.getQrCodeUrl(userId, deptId, reqDto.getCompanyUuid(), "partnerDeptQrcodeService");
		// 从缓存获取上传到七牛的URL

		BaseResponse<String> res = new BaseResponse<>();
		if(fileUrl.indexOf("失败") > -1) {
			res.setMsg(fileUrl);
			res.setCode(ResultEnum.FAIL.getNo());
			return res;
		}
		
		res.setData(fileUrl);
		res.setCode(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	/**
	 *  获取当前人员的店铺推广二维码名片
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="获取当前人员的店铺推广二维码名片")
	@PostMapping("/getPersonalCardQrCodeUrl")
	public BaseResponse<String> getPersonalCardQrCodeUrl(@RequestBody @Valid CommonReqDTO reqDto) {
		
		String fileUrl = myService.getQrCodeUrl(reqDto.getUserId(), null, reqDto.getCompanyUuid(), "partnerInfoService");
		// 从缓存获取上传到七牛的URL
		BaseResponse<String> res = new BaseResponse<>();

		if(fileUrl.indexOf("失败") > -1) {
			res.setMsg(fileUrl);
			res.setCode(ResultEnum.FAIL.getNo());
			return res;
		}
		
		res.setData(fileUrl);
		res.setCode(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
	@ApiOperation(value="获取注册页面的机构数据。入参传递为最下级ID")
	@PostMapping("/getRegesiterDeptInfo")
	public BaseResponse<String> getRegesiterDeptInfo(@RequestBody @Valid BaseRequest<GenericIdRequest> reqDto) {
		BaseResponse<String> res = new BaseResponse<>();
		String regesiterDeptInfo = myService.getRegesiterDeptInfo(reqDto.getData().getId());
		res.setData(regesiterDeptInfo);
		
		if(StringUtil.isNotNull(regesiterDeptInfo)) {
			res.setCode(ResultEnum.SUCCESS.getNo());
			res.setData(regesiterDeptInfo);
			return res;
		}
		
		res.setCode(ResultEnum.FAIL.getNo());
		res.setMsg("部门信息获取失败");
		return res;
	}
	
	
	/**
	 * 获取渠道支持
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="根据人员ID更新用户信息")
	@PostMapping("/updatePartnerInfo")
	public CommonResponse updatePartnerInfo(@RequestBody @Valid BaseRequest<UpdatePartnerInfoReqDto> reqDto) {
		UpdatePartnerInfoReqDto updatePartnerInfoReqDto = reqDto.getData();
		String accountName = updatePartnerInfoReqDto.getAccountName();
		Long partnerId = updatePartnerInfoReqDto.getPartnerId();
		String profilePhoto = updatePartnerInfoReqDto.getProfilePhoto();
		String post = updatePartnerInfoReqDto.getPost();
		PartnerInfoDto entity = new PartnerInfoDto();                                                                                                                                                               
		entity.setPost(post);
		entity.setAccountName(accountName);
		entity.setProfilePhone(profilePhoto);
		entity.setId(partnerId);
		partnerInfoService.update(entity);
		CommonResponse res = new CommonResponse(ResultEnum.SUCCESS.getNo(), "修改成功");
		return res;
	}
	
	/**
	 * 获取渠道支持
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="根据人员ID获取用户信息")
	@PostMapping("/getPartnerInfo")
	public BaseResponse<AgencyPartnerInfo> getPartnerInfo(@RequestBody @Valid BaseRequest<GenericIdRequest> reqDto) {
		Long partnerId = reqDto.getData().getId();
		BaseResponse<AgencyPartnerInfo> res = new BaseResponse<>();
		if(partnerId == null) {
			res.setCode(ResultEnum.FAIL.getNo());
			res.setMsg("人员ID传入为空");
			return res;
		}
		PartnerInfo partnerInfo = partnerInfoService.selectByAgencyId(partnerId);
		if(partnerInfo == null) {
			res.setCode(ResultEnum.FAIL.getNo());
			res.setMsg("未查到当前人员信息");
			return res;
		}
		AgencyPartnerInfo agencyPartnerInfo = new AgencyPartnerInfo();
		agencyPartnerInfo.setAccountName(partnerInfo.getAccountName());
		agencyPartnerInfo.setPhone(partnerInfo.getPhone());
		agencyPartnerInfo.setPost(partnerInfo.getPost());
		String profilePhoto = partnerInfo.getProfilePhoto();
		if(StringUtil.isNotNull(profilePhoto)) {
			String newProfilePhoto = QiNiuUtil.convertFileToQiniu(profilePhoto);
			if(!profilePhoto.equals(newProfilePhoto)) {
				//设置返回链接，更新楼盘返回值
				profilePhoto = newProfilePhoto;
				PartnerInfoDto entity = new PartnerInfoDto();
				entity.setId(partnerInfo.getId());
				entity.setProfilePhone(profilePhoto);
				partnerInfoService.update(entity );
			}
		}
		agencyPartnerInfo.setProfilePhoto(profilePhoto);
		agencyPartnerInfo.setDevCompanyUuid(partnerInfo.getDevCompanyUuid());
		res.setData(agencyPartnerInfo);
		res.setCode(ResultEnum.SUCCESS.getNo());
		return res;
	}


	/**
	 * 获取当前登录人的项目列表
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="获取当前登录人的项目列表")
	@PostMapping("/getMyPremisesList")
	public BaseResponse<GetPremisesListResDto> getMyPremisesList(@RequestBody @Valid BaseRequest<GetPremisesListReqDto> reqDto) {
		GetPremisesListReqDto getPremisesListReqDto = reqDto.getData();
		BaseResponse<GetPremisesListResDto> res = new BaseResponse<GetPremisesListResDto>();
		GetPremisesListResDto resDto = new GetPremisesListResDto();
		try {
			resDto = premisesService.getPremisesList(getPremisesListReqDto);
		} catch (Exception e) {
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("获取项目失败!");
		}
		res.setData(resDto);
		res.setCode(ResultEnum.SUCCESS.getNo());
		return res;
	}



	/**
	 * 获取当前登录人的客户报备和客户到访
	 * @param commonReqDto
	 * @return
	 */
	@ApiOperation(value="获取当前登录人的客户报备和客户到访")
	@PostMapping("/getMyCustomerCount")
	public BaseResponse<GetCustomerCountRes> getMyCustomerCount(@RequestBody @Valid BaseRequest<GetMyCustomerCountReqDto> reqDto) {
		BaseResponse<GetCustomerCountRes> res = new BaseResponse<>();
		GetMyCustomerCountReqDto getMyCustomerCountReqDto = reqDto.getData();
		GetMyCustomerCountReqDto reqData = new GetMyCustomerCountReqDto();
		String userId  = getMyCustomerCountReqDto.getUserId();
		if(userId == null) {
			res.setCode(ResultEnum.FAIL.getNo());
			res.setMsg("人员ID传入为空");
			return res;
		}
		Long companyId = getMyCustomerCountReqDto.getCompanyId();
		String startTime = getMyCustomerCountReqDto.getStartTime();
		String endTime = getMyCustomerCountReqDto.getEndTime();
		reqData.setCompanyId(companyId);
		reqData.setStartTime(startTime);
		reqData.setEndTime(endTime);
		reqData.setUserId(userId);
		CustomerCount customerCount = channelReportService.getCustomerCount(reqData);
		GetCustomerCountRes result = new GetCustomerCountRes();
		result.setSuccessCount(customerCount.getSuccessCount());
		result.setComeToCount(customerCount.getComeToCount());
		res.setData(result);
		res.setCode(ResultEnum.SUCCESS.getNo());
		return res;
	}
	
}
